<template>
	<div class="p-6 space-y-6">

		<el-card>
			<div class="flex justify-between items-center mb-2">
				<h3 class="text-lg font-semibold">🛒 我的购物车</h3>
				<div>
					<el-button size="small" type="success" @click="showPayDialog = true"
						v-if="cart.length">支付所选</el-button>
					<el-button size="small" type="danger" @click="clearCart" v-if="cart.length">清空购物车</el-button>
				</div>
			</div>
			<el-table v-if="cart.length" :data="cart" border @selection-change="onSelectionChange">
				<el-table-column type="selection" width="55" />
				<el-table-column prop="name" label="商品" />
				<el-table-column prop="quantity" label="数量" />
				<el-table-column prop="price" label="单价" />
				<el-table-column label="操作">
					<template #default="{ row }">
						<el-button size="small" type="danger" @click="deleteFromCart(row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-empty v-else description="购物车为空" />
		</el-card>

		<el-dialog v-model="showPayDialog" title="确认支付" width="400px">
			<p>您将购买以下商品：</p>
			<ul class="text-sm list-disc list-inside mt-2">
				<li v-for="item in selectedItems" :key="item.name">
					{{ item.name }} × {{ item.quantity }} = ¥{{ (parseFloat(item.price) * item.quantity).toFixed(2) }}
				</li>
			</ul>
			<p class="text-right font-bold mt-4">总计：¥{{ selectedTotal }}</p>
			<div class="text-center mt-4">
				<el-button type="primary" @click="payCart">确认支付</el-button>
				<el-button @click="showPayDialog = false">取消</el-button>
			</div>
		</el-dialog>

		<el-card>
			<div class="flex justify-between items-center mb-2">
				<h3 class="text-lg font-semibold">⭐ 我的收藏夹</h3>
				<el-button size="small" type="danger" @click="clearFavorites" v-if="favorites.length">清空收藏夹</el-button>
			</div>
			<el-table :data="favorites" v-if="favorites.length" border>
				<el-table-column prop="name" label="商品" />
				<el-table-column prop="category" label="分类" />
				<el-table-column label="操作">
					<template #default="{ row }">
						<el-button size="small" @click="goToDetail(row)">详情</el-button>
						<el-button size="small" type="danger" @click="deleteFromFavorites(row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-empty v-else description="暂无收藏" />
		</el-card>
	</div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()
const cart = ref([])
const favorites = ref([])
const showPayDialog = ref(false)
const selectedItems = ref([])

const refreshData = () => {
	cart.value = JSON.parse(localStorage.getItem('cart') || '[]')
	favorites.value = JSON.parse(localStorage.getItem('favorites') || '[]')
}

const onSelectionChange = (val) => {
	selectedItems.value = val
}

const deleteFromCart = (item) => {
	cart.value = cart.value.filter(i => i !== item)
	localStorage.setItem('cart', JSON.stringify(cart.value))
}

const deleteFromFavorites = (item) => {
	favorites.value = favorites.value.filter(i => i !== item)
	localStorage.setItem('favorites', JSON.stringify(favorites.value))
}

const clearCart = () => {
	cart.value = []
	localStorage.removeItem('cart')
	selectedItems.value = []
}

const clearFavorites = () => {
	favorites.value = []
	localStorage.removeItem('favorites')
}

const selectedTotal = computed(() => {
	return selectedItems.value.reduce((sum, item) => sum + item.quantity * parseFloat(item.price), 0).toFixed(2)
})

const payCart = () => {
	if (!selectedItems.value.length) return
	const orders = JSON.parse(localStorage.getItem('orders') || '[]')
	const now = new Date().toLocaleString()
	selectedItems.value.forEach(item => {
		orders.push({
			id: Date.now() + Math.random(),
			name: item.name,
			quantity: item.quantity,
			total: (parseFloat(item.price) * item.quantity).toFixed(2),
			time: now
		})
	})
	localStorage.setItem('orders', JSON.stringify(orders))
	ElMessage.success('支付成功，订单已生成')
	cart.value = cart.value.filter(i => !selectedItems.value.includes(i))
	localStorage.setItem('cart', JSON.stringify(cart.value))
	showPayDialog.value = false
	selectedItems.value = []
}

const goToDetail = (item) => {
	const id = getProductIdByName(item.name)
	if (id) router.push({ name: 'ProductDetail', params: { id } })
	else ElMessage.warning('无法跳转：商品 ID 不存在')
}

const getProductIdByName = (name) => {
	const map = {
		'EUV光刻胶 - 光刻材料': 1,
		'G线光刻胶 - 光刻材料': 2,
		'紫外宽谱光刻胶 - 光刻材料': 3,
		'电子光束刻胶 - 光刻材料': 4,
		'氧化硅抛光液 - 抛光材料': 5,
		'氧化铝抛光液 - 抛光材料': 6,
		'纳米抛光液 - 抛光材料': 7,
		'显影液 - 工艺化学品': 8,
		'去胶剂 - 工艺化学品': 9,
		'清洗剂 - 工艺化学品': 10,
		'蚀刻液 - 工艺化学品': 11
	}
	return map[name] || null
}

onMounted(() => {
	if (!localStorage.getItem('cart')) {
		const mockCart = [
			{ name: 'EUV光刻胶 - 光刻材料', quantity: 2, price: '420.00' },
			{ name: 'G线光刻胶 - 光刻材料', quantity: 1, price: '310.50' },
			{ name: '氧化硅抛光液 - 抛光材料', quantity: 3, price: '150.00' },
			{ name: '蚀刻液 - 工艺化学品', quantity: 2, price: '198.88' },
			{ name: '去胶剂 - 工艺化学品', quantity: 1, price: '266.66' }
		]
		localStorage.setItem('cart', JSON.stringify(mockCart))
	}
	if (!localStorage.getItem('favorites')) {
		const mockFav = [
			{ name: 'EUV光刻胶 - 光刻材料', category: '光刻材料' },
			{ name: '纳米抛光液 - 抛光材料', category: '抛光材料' },
			{ name: '显影液 - 工艺化学品', category: '工艺化学品' },
			{ name: '清洗剂 - 工艺化学品', category: '工艺化学品' },
			{ name: '电子光束刻胶 - 光刻材料', category: '光刻材料' }
		]
		localStorage.setItem('favorites', JSON.stringify(mockFav))
	}
	refreshData()
})

</script>

<style scoped>
.text-xl {
	font-size: 1.25rem;
}
</style>
  
